/*
 * User: user
 * Date: 11/02/2008
 * Time: 18:08:32
 */
package org.conann.instrument;

import org.conann.exceptions.WebBeansException;
import org.conann.util.AnnotationUtil;
import static org.conann.util.AnnotationUtil.getRelevantAnnotations;

import javax.webbeans.Manager;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

public class WebBeanUtil {

    private static final Manager MANAGER = null;

    public static void initialize(Object instance) {
        for (Field field : getManagedFields(instance.getClass())) {
            initializeField(instance, field);
        }
    }

    private static void initializeField(Object instance, Field field) {
        Set<Annotation> relevantAnnotations = AnnotationUtil.getRelevantAnnotations(field);
        Annotation[] annotations = relevantAnnotations.toArray(new Annotation[relevantAnnotations.size()]);
        Object fieldInstance = MANAGER.getInstanceByType(field.getType(), annotations);
        try {
            field.setAccessible(true);
            field.set(instance, fieldInstance);
        } catch (IllegalAccessException e) {
            throw new WebBeansException("", e);
        }
    }

    private static Set<Field> getManagedFields(Class<?> type) {
        Set<Field> fields = new HashSet<Field>(4);
        for (Field field : type.getDeclaredFields()) {
            if (!getRelevantAnnotations(field).isEmpty()) {
                fields.add(field);
            }
        }
        return fields;
    }
}